<template>
  <div>
    <div v-if="componentIs('personal')" class="mod-config" id="mod-config-id">
      <div v-if="isAuth('personal:paging')" class="div-s" id="div-s-id">
        <el-form :model="params" :label-position="labelPosition" :inline="true" label-width="70px" class="queryFormed">
          <el-row class="row-s">
            <el-col v-if="isAuth('personal:transfer')" :span="6">
              <el-form-item label="跟进人">
                <el-select v-model="employeeSelectValue" placeholder="请选择部门/人"  @clear="clearEmployee"  @focus="showSelectEmployeeDialog"  clearable no-data-text=" "></el-select>
              </el-form-item>
            </el-col>
            <el-col class="col-center" :span="6">
              <el-form-item label="联系人" prop="contactsName">
                <el-input v-model="params.contactsName" placeholder="请输入联系人" @clear="clearContactsName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col class="col-center" :span="6">
              <el-form-item label="手机号" prop="contactsMobile">
                <el-input v-model="params.contactsMobile" placeholder="请输入联系人手机号" @clear="clearContactsMobile"  clearable>

                </el-input>
              </el-form-item>
            </el-col>
            <el-col :class="{'col-right' : isManager }"  :span="6">
              <el-form-item label="消费次数">
                <div style="display: flex">
                    <el-input  v-model="params.costAmountLower" class="input-width" oninput="value=value.replace(/[^\d]/g,'')" placeholder="0" style="width: 80px" @clear="clickSearch" clearable></el-input>
                      <div style="display: inline-block;padding: 0 3px">~</div>
                    <el-input  v-model="params.costAmountUpper" class="input-width" oninput="value=value.replace(/[^\d]/g,'')" placeholder="99"   style="width: 80px" @clear="clickSearch" clearable></el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col  class="col-center" :span="6">
              <el-form-item >
                <el-checkbox v-model="params.mainlyFlag" :true-label="1" :false-label="0" @change="changeMainlyFlag">近期重点客户</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col  class="col-center" :span="6">
              <el-form-item >
                <el-checkbox v-model="params.unFollowFlag" :true-label="1" :false-label="0" @change="changeUnfollowFlag">一个月未跟进客户</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col  class="col-center" :span="6">
              <el-form-item >
                <el-checkbox v-model="params.transferRecentFlag" :true-label="1" :false-label="null" @change="clickSearch">近期转让</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col class="col-right" :span="6" :offset=" isManager ? 0 : 12">
              <el-form-item class="item-all">
                <el-button class="buttonItem" size="mini" plain @click="clickReset()">重 置</el-button>
                <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch()">搜 索</el-button>
<!--                <el-button v-if="!isUnfold" @click="turnFoldState" type="text">展开<i
                  class="el-icon-arrow-down zhankai"></i></el-button>
                <el-button v-if="isUnfold" @click="turnFoldState" type="text">收起<i class="el-icon-arrow-up zhankai"></i>
                </el-button>-->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="div-e" id="div-e-id">
        <div class="div-inquire" id="div-inquire-id">
          <div class="in-t">
            <div class="in-ts"></div>
            <h3 >个人成交</h3>
          </div>
          <div  class="div-button">
            <batch-import :type="0" :customerType="1" v-if="isAuth('personal:import')" @refreshData="refreshData"></batch-import>
<!--            <el-button v-if="isAuth('ent:customer:personImport')" size="mini" type="primary" icon="el-icon-download">批量导入</el-button>-->
            <el-button v-if="isAuth('personal:export')" size="mini" type="primary" icon="el-icon-upload2" @click="clickExport">数据导出</el-button>
            <el-button v-if="isAuth('personal:transfer')" size="mini" type="primary" @click="showSelectEmployeeTransferDialog" :disabled="customerIdList.length <1">批量转让</el-button>
            <el-button size="mini" type="primary" @click="markMainly" :disabled="customerIdList.length <1">标记重点客户</el-button>
            <el-button size="mini" type="danger" @click="unmarkMainly" :disabled="customerIdList.length <1">取消标记重点客户</el-button>
            <el-button v-if="isAuth('personal:save')" size="mini" type="primary" icon="el-icon-plus" @click="showAddOrUpdateDialog('add-or-update')">新增</el-button>
          </div>

        </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          :max-height="table.tableHeight"
          :header-cell-style="{background:'#F5F7FA'}"
          :cell-style="{'border-right': 'none','border-left': 'none'}"
          style="width: 100%"
          v-loading="dataListLoading"
          @selection-change="handleSelectionChange"
          border>
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="序号"
            type="index"
            width="70"
            align="center"
            fixed>
            <template slot-scope="scope">
              <div class="importFlagBox" ><img  v-if="scope.row.mainlyFlag === 1" src="../../../assets/img/importCustomer2x.png" alt="重点客户图标"><span class="boxIndex">{{scope.$index + 1}}</span></div>
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            width="100"
            prop="name"
            align="center"
          show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.name}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="contactsMobile"
            label="联系方式"
            width="130"
            align="center"
          show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.contactsMobile}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="mailingAddress"
            label="邮寄地址"
            align="center"
            min-width="180"
          show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.mailingAddress}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="totalCost"
            label="消费总额（元）"
            width="120"
            align="center"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.totalCost}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="costAmount"
            label="消费次数"
            width="100"
            align="center"
          show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.costAmount}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="followUserName"
            label="跟进人"
            width="80"
            align="center"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.followUserName}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="lastDealTime"
            label="最后成交时间"
            align="center"
            width="130"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.lastDealTime}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="lastFollow"
            label="最新跟进"
            align="center"
            min-width="200"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="[ scope.row.mainlyFlag === 1 ? 'import-color' : scope.row.unFollowFlag === 1 ? 'warning-color': '']">
                {{scope.row.lastFollow}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="transferDates"
            label="转让天数"
            min-width="120"
            align="center"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            min-width="110">
            <template slot-scope="scope">
              <el-button type="text" size="mini" style="color: #66b1ff" @click="showDetails('details', scope.row)">跟进</el-button>
              <span style="color:#E8E8E8;">|</span>
              <el-popover
                placement="bottom"
                :visible-arrow="false"
                popper-class="popper-style">
                <div style="text-align: center; margin: 0; display: flex;flex-direction: column;font-size: 12px">
                  <div v-if="isAuth('personal:transfer')" type="text" @click="clickTransferSingle(scope.row)" class="popover-item">转让</div>
                  <div v-if="isAuth('personal:delete')" type="text" @click="clickDelete(scope.row)" class="popover-item">删除</div>
                </div>
                <el-button type="text" size="mini" slot="reference"  style="color: #66b1ff">更多<i
                  class="el-icon-arrow-down"></i></el-button>
              </el-popover>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="changePageSize"
          @current-change="turnToPage"
          :current-page="queryInfo.pageIndex"
          :page-sizes="[5, 10, 20, 50, 100, 200]"
          :page-size="queryInfo.pageSize "
          layout="total, prev, pager, next, sizes, jumper"
          :total="totalPage"
          id="div-e-paging-id">
        </el-pagination>
      </div>
      <el-dialog
        title=""
        :visible.sync="selectEmployeeDialogVisible"
        top="20vh"
        width="35%">
      <h3 slot="title">
        选择部门/人
      </h3>
        <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
          <el-tree :data="employeeTreeList" ref="employeeQueryTreeRefs" :props="defaultProps" @node-click="employeeHandleNodeClick "></el-tree>
        </div>
        <span style="display: flex;justify-content: center;">
        <el-button @click="selectEmployeeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSelectEmployeeSearch">确 认</el-button>
      </span>
      </el-dialog>
      <el-dialog
        title=""
        :visible.sync="selectEmployeeTransferDialogVisible"
        top="20vh"
        width="35%"
        @closed="()=>{this.employeeId=null;this.customerIdList=[];this.$refs.multipleTable.clearSelection()}">
      <h3 slot="title">
        选择部门/人
      </h3>
        <div style="border: 1px solid #DDDDDD;border-radius: 2px;height: 30vh;overflow: auto;margin: 0 40px 28px 40px;padding: 13px 20px">
          <el-tree :data="employeeTreeList" ref="employeeTransferTreeRefs" :props="defaultProps" @node-click="employeeTransferHandleNodeClick "></el-tree>
        </div>
        <span style="display: flex;justify-content: center;">
        <el-button @click="selectEmployeeTransferDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickConfirmTransfer">确 认</el-button>
      </span>
      </el-dialog>
    </div>
    <add-or-update v-if="componentIs('add-or-update') " :isAdd="true"></add-or-update>
    <personal-details v-if="componentIs('details')" :id="customerId"></personal-details>
  </div>
</template>

<script>
import BasePaging from '../../common/BasePaging'
import AddOrUpdate from './Component/personal/add-or-update'
import PersonalDetails from './Component/personal/Details'
import {paging} from '../../../api/customer/potential'
import {getRegionTree} from '../../../api/customer/region'
import {getUserInfo} from '../../../api/sys'
import {getDepartTree} from '../../../api/depart'
import {isAuth} from '../../../utils'
import BatchImport from './Component/BatchImport'
import {
  customerExport,
  markMainly,
  unmarkMainly,
  transferCustomerBatch
} from '../../../api/customer/enterprise'
import {deleteCustomer} from '../../../api/customer/regionalList'
const isObjHasKey = require('lodash/has')
export default {
  name: 'personal',
  components: {PersonalDetails, BatchImport, AddOrUpdate},
  extends: BasePaging,
  created () {
    this.getUserInfo()
    if (isAuth('personal:paging')) {
      this.paging()
    }
  },
  data () {
    return {
      isAdd: true,
      bodyHeight: 0,
      searchHeight: 0,
      inqerts: false,
      userInfo: {},
      customerId: '',
      params: {
        followUserId: '',
        name: '',
        contactsName: '',
        contactsMobile: '',
        mainlyFlag: 0,
        unFollowFlag: 0,
        employeeId: '',
        costAmountLower: '',
        costAmountUpper: '',
        deptId: '',
        transferRecentFlag: null
      },
      labelPosition: 'left',
      componentFlag: 'personal',
      employeeSelectValue: '',
      areaSelectValue: '',
      dataListLoading: false,
      selectPeopleDialogVisible: false,
      selectAreaDialogVisible: false,
      selectEmployeeDialogVisible: false,
      selectEmployeeTransferDialogVisible: false,
      popoverVisible: false,
      addOrUpdateVisible: false,
      tableData: [],
      departTreeList: [],
      employeeTreeList: [],
      areaTreeList: [],
      customerIdList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },

  methods: {
    isAuth (auth) {
      return isAuth(auth)
    },
    // 初始化参数
    initParams () {
      this.params.mainlyFlag = 0
      this.params.unFollowFlag = 0
      Object.keys(this.params).forEach((key) => { this.params[key] = '' })
    },
    refreshData () {
      this.initParams()
      this.paging()
    },
    // 判断当前什么组件
    componentIs (val) {
      return this.componentFlag === val
    },
    // 更改组件显示
    changeComponent (to) {
      this.componentFlag = to
      this.paging()
    },
    checkCostAmount (lower, upper) {
      lower = Number(lower)
      upper = Number(upper)
      if (lower && upper && lower > upper) {
        [lower, upper] = [upper, lower]
      }
      this.params.costAmountUpper = upper
      this.params.costAmountLower = lower
      if (lower === 0) {
        this.params.costAmountLower = ''
      }
      if (upper === 0) {
        this.params.costAmountUpper = ''
      }
    },
    paging () {
      this.checkCostAmount(this.params.costAmountLower, this.params.costAmountUpper)
      this.dataListLoading = true
      paging(
        '/ent/customer/paging',
        {
          'conditions': {
            'typeId': 1,
            'enterpriseFlag': 0,
            'followUserId': this.params.followUserId,
            'name': this.params.name,
            'contactsName': this.params.contactsName,
            'contactsMobile': this.params.contactsMobile,
            'mainlyFlag': this.params.mainlyFlag,
            'unFollowFlag': this.params.unFollowFlag,
            'costAmountLower': this.params.costAmountLower,
            'costAmountUpper': this.params.costAmountUpper,
            'deptId': this.params.deptId,
            'transferRecentFlag': this.params.transferRecentFlag
          },
          'inOrder': '',
          'orderBy': '',
          'pageNum': this.queryInfo.pageIndex,
          'pageSize': this.queryInfo.pageSize
        },
        'post',
        (data) => {
          this.tableData = data.data.records
          this.totalPage = data.data.total
          this.dataListLoading = false
        }
      )
    },
    handleSelectionChange (selection) {
     //  console.log('selection', selection)
      this.customerIdList = selection.map(item => item.id)
    },
    showAddOrUpdateDialog (val) {
      this.changeComponent(val)
    },
    showDetails (val, row) {
      this.customerId = row.id
      this.changeComponent(val)
    },

    // 点击重置
    clickReset () {
      this.initParams()
      this.employeeSelectValue = ''
      this.paging()
    },
    getEmployeeTree (action = 2) {
      getDepartTree(
        action,
        (data) => {
          this.transformEmployeeTreeData(data.data)
          this.employeeTreeList = data.data
        }
      )
    },
    showSelectEmployeeDialog () {
      this.getEmployeeTree(2)
      this.selectEmployeeDialogVisible = true
    },

    // 部门人员数据转换为符合组件使用的类型
    transformEmployeeTreeData (data = []) {
      if (data) {
        data.forEach((item) => {
          item.name = item.deptName
          if (item.children && item.userList) {
            this.transformEmployeeTreeData(item.children)
            item.children = item.children.concat(item.userList)
          } else if (!item.children && item.userList) {
            item.children = item.userList
          }
        })
      }
    },
    // 清空
    clearEmployee () {
      this.params.followUserId = ''
      this.clickSearch()
    },
    clearContactsName () {
      this.clickSearch()
    },
    clearContactsMobile () {
      this.clickSearch()
    },
    changeMainlyFlag () {
      this.clickSearch()
    },
    changeUnfollowFlag () {
      this.clickSearch()
    },
    // 选择部门对话框
    employeeHandleNodeClick (nodeObj, node) {
      this.employeeSelectValue = node.data.name
      if (node.isLeaf) {
        this.params.deptId = null
        this.params.followUserId = node.data.id
      } else {
        this.params.followUserId = null
        this.params.deptId = node.data.id
      }
    },
    // 选择区域对话框
    areaHandleNodeClick (nodeObj, node) {
      this.areaSelectValue = node.data.name
      this.params.areaId = node.data.id
    },
    showSelectAreaDialog () {
/*      getAreaTree(
        '/ent/area/tree',
        {'actionId': 1},
        'get',
        (data) => {
          this.areaTreeList = data.data
        } */
      getRegionTree({'actionId': 1}, (data) => {
        this.areaTreeList = data.data
      })

      this.selectAreaDialogVisible = true
    },
    // 确认转让
    clickConfirmTransfer () {
      let curNode = this.$refs.employeeTransferTreeRefs.getCurrentNode()
      if (this.customerIdList && this.employeeId) {
        // 用来判断选择是否是部门
        let isDept = isObjHasKey(curNode, 'userList')
        if (!isDept) {
          this.$prompt('请输入转让日志', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            inputValidator: function (value) {
              if (!value) {
                return '转让日志不得为空!'
              } else if (value.length < 20 && value.length > 0) {
                let currlen = value.length
                return `日志长度至少为20字,当前长度为${currlen}`
              } else {
                return true
              }
            }
          }).then(({value}) => {
            transferCustomerBatch({customerIdList: this.customerIdList, userId: this.employeeId, remark: value},
              () => {
                this.$message.success('转让成功!')
                this.paging()
              })
            this.selectEmployeeTransferDialogVisible = false
          })
        } else {
          this.$message.warning('只能转让给部门下的人员，重新选择。')
        }
      } else {
        this.selectEmployeeTransferDialogVisible = false
      }
    },
    employeeTransferHandleNodeClick (node) {
      this.employeeId = node.id
    },
    markMainly () {
      markMainly(this.customerIdList, () => { this.paging() })
    },

    // 取消标记重点客户
    unmarkMainly () {
      unmarkMainly(this.customerIdList, () => { this.paging() })
    },
    // 显示批量转让对话框
    showSelectEmployeeTransferDialog () {
      this.getEmployeeTree(1)
      this.selectEmployeeTransferDialogVisible = true
    },
    // 单条转让
    clickTransferSingle (row) {
      this.customerIdList = []
      this.customerIdList.push(row.id)
      this.showSelectEmployeeTransferDialog()
    },
    // 点击删除客户
    clickDelete (row) {
      this.$confirm(`确定要删除“${row.name}”吗？`, '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消',
        type: 'warning'
      }).then(() => {
        deleteCustomer(row.id, () => { this.paging() })
        // removeCustomer(row.id)
        // this.paging()
      })
    },
    getUserInfo () {
      getUserInfo((data) => {
        this.userInfo = data.user
      })
    },
    clickExport () {
      customerExport(
        { 'typeId': 1,
          'enterpriseFlag': 0,
          ...this.params},
        '个人成交导出'
      )
    },
    clickSelectEmployeeSearch () {
      this.clickSearch()
      this.selectEmployeeDialogVisible = false
    }

  },
  computed: {
    isManager () {
      return this.userInfo.managerFlag === 1
    }
  }
}
</script>
